<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-alert title="消息提示的文案" type="info" show-icon center></el-alert>
      <el-steps :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addGoodsForm"
        :rules="addGoodsRules"
        ref="addGoodsRef"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="tabsChange"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="cateData"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyTableData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(cb,i) in item.attr_vals" :key="i" :label="cb" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              label-position="top"
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce" />
            <el-button @click="subAddGoods" class="addGoods" type="primary" round>添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="30%">
      <img :src="previewPath" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from "loadsh";
export default {
  data() {
    return {
      activeIndex: "0",
      // 添加商品的表单数据
      addGoodsForm: {
        goods_name: "",
        goods_price: "0",
        goods_weight: "0",
        goods_number: "0",
        // 选中的分类
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: []
      },
      // 添加商品校验规则
      addGoodsRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" }
        ]
      },
      cateData: [],
      cateProps: { expandTrigger: "hover", label: "cat_name", value: "cat_id" },
      manyTableData: [],
      onlyTableData: [],
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      headerObj: { Authorization: window.sessionStorage.getItem("token") },
      previewPath: "",
      previewDialogVisible: false
    };
  },

  created() {

    this.getCateList();
  },

  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("分类列表加载失败");
      this.cateData = res.data;
    },
    // 级联选择器选择时触发
    handleChange() {
      if (this.addGoodsForm.goods_cat.length !== 3)
        return (this.addGoodsForm.goods_cat = []);
    },
    tabsChange(activeName, oldActiveName) {
      if (oldActiveName == 0 && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    async tabClick() {
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" }
          }
        );
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });
        this.manyTableData = res.data;
      } else if (this.activeIndex === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" }
          }
        );
        this.onlyTableData = res.data;
      }
    },
    // 图片预览
    handlePreview(file) {
      this.previewPath = file.response.data.url;
      this.previewDialogVisible = true;
    },
    // 图片移除
    handleRemove(file) {
      const filePath = file.response.data.tmp_path;
      const deleteIndex = this.addGoodsForm.pics.findIndex(x => {
        x.pic === filePath;
      });
      this.addGoodsForm.pics.splice(deleteIndex, 1);
    },
    // 图片上传成功
    handleSuccess(response) {
      // 1.定义一个对象存放图片上传地址
      const picInfo = { pic: response.data.tmp_path };
      // 2.将改对象push到表单数据的pics数组中
      this.addGoodsForm.pics.push(picInfo);
    },
    // 点击添加商品提交
    subAddGoods() {
      this.$refs.addGoodsRef.validate(async flag => {
        if (!flag) return this.$message.error("请填写必要的参数");
        const copyForm = _.cloneDeep(this.addGoodsForm);
        copyForm.goods_cat = copyForm.goods_cat.join(",");
        // 处理动态参数的attrs
        this.manyTableData.forEach(item => {
          const newObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" ")
          };
          this.addGoodsForm.attrs.push(newObj);
        });
        // 处理静态属性的attrs
        this.onlyTableData.forEach(item => {
          const newObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          };
          this.addGoodsForm.attrs.push(newObj);
        });
        // copyForm.attrs赋值为addGoodsForm.attrs
        copyForm.attrs = this.addGoodsForm.attrs;
        // 提交添加商品
        const { data: res } = await this.$http.post("goods", copyForm);
        if (res.meta.status !== 201) return this.$message.error("商品添加失败");
        this.$message.success("商品添加成功");
        this.$router.push("/goods");
      });
    }
  },
  computed: {
    cateId() {
      if (this.addGoodsForm.goods_cat.length === 3)
        return this.addGoodsForm.goods_cat[2];
    }
  }
};
</script>

<style scoped lang='less'>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.addGoods {
  margin-top: 20px;
}
</style>
